package java8;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * \* User: MeiZhongHao
 * \* Date: 2019-05-29
 * \* Time: 14:18
 * \* Description:
 * \
 */
public class TestJava8 {


    public static void main(String[] args) {

        List<String> alpha = Arrays.asList(new String[]{"a", "b", "c", "d"});

        //Before Java8
        List<String> alphaUpper = new ArrayList<>();
        for (String s : alpha) {
            alphaUpper.add(s.toUpperCase());
        }

        System.out.println(alpha); //[a, b, c, d]
        System.out.println(alphaUpper); //[A, B, C, D]

        // Java 8
        List<String> collect = alpha.stream().map(String::toUpperCase).collect(Collectors.toList());
        System.out.println(collect); //[A, B, C, D]

        // Extra, streams apply to any data type.
        List<Integer> num = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> collect1 = num.stream().map(n -> n * 2).collect(Collectors.toList());
        System.out.println(collect1); //[2, 4, 6, 8, 10]

        Map<Integer, Integer> map = num.stream().map(n -> n * 2).collect(Collectors.toMap(n -> n, n -> n * 2));
        System.out.println(JSON.toJSONString(map));

        Stream<String> words1 = Arrays.asList(new String[]{"your", "name"}).stream();
        Stream<String> words2 = Arrays.asList(new String[]{"your", "name"}).stream();

        List result = words1.map(w -> {
            List<Character> ii = new ArrayList<>();
            for (char c : w.toCharArray())
                ii.add(c);
            return ii;
        }).collect(Collectors.toList());
        // [[y, o, u, r], [n, a, m, e]]
        System.out.println(result);

        List letters = words2.flatMap(w -> {
                    List<Character> ii = new ArrayList<>();
                    for (char c : w.toCharArray())
                        ii.add(c);
                    return ii.stream();
                }
        ).collect(Collectors.toList());
        // [y, o, u, r, n, a, m, e]
        System.out.println(letters);
    }
}